/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package daos;

import daos.exceptions.IllegalOrphanException;
import daos.exceptions.NonexistentEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Company;
import entities.Quote;
import entities.Stock;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Juan
 */
public class StockJpaController implements Serializable {
    private static StockJpaController instance;
    
    public synchronized static StockJpaController getInstance(){
        if(instance == null){
            instance = new StockJpaController();
        }
        return instance;
    }

    public StockJpaController() {
        this.emf = Persistence.createEntityManagerFactory("JavaApplication9PU");
    }
    
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Stock stock) {
        if (stock.getQuoteCollection() == null) {
            stock.setQuoteCollection(new ArrayList<Quote>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Company idcompany = stock.getIdcompany();
            if (idcompany != null) {
                idcompany = em.getReference(idcompany.getClass(), idcompany.getId());
                stock.setIdcompany(idcompany);
            }
            Collection<Quote> attachedQuoteCollection = new ArrayList<Quote>();
            for (Quote quoteCollectionQuoteToAttach : stock.getQuoteCollection()) {
                quoteCollectionQuoteToAttach = em.getReference(quoteCollectionQuoteToAttach.getClass(), quoteCollectionQuoteToAttach.getId());
                attachedQuoteCollection.add(quoteCollectionQuoteToAttach);
            }
            stock.setQuoteCollection(attachedQuoteCollection);
            em.persist(stock);
            if (idcompany != null) {
                idcompany.getStockCollection().add(stock);
                idcompany = em.merge(idcompany);
            }
            for (Quote quoteCollectionQuote : stock.getQuoteCollection()) {
                Stock oldIdstockOfQuoteCollectionQuote = quoteCollectionQuote.getIdstock();
                quoteCollectionQuote.setIdstock(stock);
                quoteCollectionQuote = em.merge(quoteCollectionQuote);
                if (oldIdstockOfQuoteCollectionQuote != null) {
                    oldIdstockOfQuoteCollectionQuote.getQuoteCollection().remove(quoteCollectionQuote);
                    oldIdstockOfQuoteCollectionQuote = em.merge(oldIdstockOfQuoteCollectionQuote);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Stock stock) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Stock persistentStock = em.find(Stock.class, stock.getId());
            Company idcompanyOld = persistentStock.getIdcompany();
            Company idcompanyNew = stock.getIdcompany();
            Collection<Quote> quoteCollectionOld = persistentStock.getQuoteCollection();
            Collection<Quote> quoteCollectionNew = stock.getQuoteCollection();
            List<String> illegalOrphanMessages = null;
            for (Quote quoteCollectionOldQuote : quoteCollectionOld) {
                if (!quoteCollectionNew.contains(quoteCollectionOldQuote)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Quote " + quoteCollectionOldQuote + " since its idstock field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idcompanyNew != null) {
                idcompanyNew = em.getReference(idcompanyNew.getClass(), idcompanyNew.getId());
                stock.setIdcompany(idcompanyNew);
            }
            Collection<Quote> attachedQuoteCollectionNew = new ArrayList<Quote>();
            for (Quote quoteCollectionNewQuoteToAttach : quoteCollectionNew) {
                quoteCollectionNewQuoteToAttach = em.getReference(quoteCollectionNewQuoteToAttach.getClass(), quoteCollectionNewQuoteToAttach.getId());
                attachedQuoteCollectionNew.add(quoteCollectionNewQuoteToAttach);
            }
            quoteCollectionNew = attachedQuoteCollectionNew;
            stock.setQuoteCollection(quoteCollectionNew);
            stock = em.merge(stock);
            if (idcompanyOld != null && !idcompanyOld.equals(idcompanyNew)) {
                idcompanyOld.getStockCollection().remove(stock);
                idcompanyOld = em.merge(idcompanyOld);
            }
            if (idcompanyNew != null && !idcompanyNew.equals(idcompanyOld)) {
                idcompanyNew.getStockCollection().add(stock);
                idcompanyNew = em.merge(idcompanyNew);
            }
            for (Quote quoteCollectionNewQuote : quoteCollectionNew) {
                if (!quoteCollectionOld.contains(quoteCollectionNewQuote)) {
                    Stock oldIdstockOfQuoteCollectionNewQuote = quoteCollectionNewQuote.getIdstock();
                    quoteCollectionNewQuote.setIdstock(stock);
                    quoteCollectionNewQuote = em.merge(quoteCollectionNewQuote);
                    if (oldIdstockOfQuoteCollectionNewQuote != null && !oldIdstockOfQuoteCollectionNewQuote.equals(stock)) {
                        oldIdstockOfQuoteCollectionNewQuote.getQuoteCollection().remove(quoteCollectionNewQuote);
                        oldIdstockOfQuoteCollectionNewQuote = em.merge(oldIdstockOfQuoteCollectionNewQuote);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = stock.getId();
                if (findStock(id) == null) {
                    throw new NonexistentEntityException("The stock with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Stock stock;
            try {
                stock = em.getReference(Stock.class, id);
                stock.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The stock with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Quote> quoteCollectionOrphanCheck = stock.getQuoteCollection();
            for (Quote quoteCollectionOrphanCheckQuote : quoteCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Stock (" + stock + ") cannot be destroyed since the Quote " + quoteCollectionOrphanCheckQuote + " in its quoteCollection field has a non-nullable idstock field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Company idcompany = stock.getIdcompany();
            if (idcompany != null) {
                idcompany.getStockCollection().remove(stock);
                idcompany = em.merge(idcompany);
            }
            em.remove(stock);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Stock> findStockEntities() {
        return findStockEntities(true, -1, -1);
    }

    public List<Stock> findStockEntities(int maxResults, int firstResult) {
        return findStockEntities(false, maxResults, firstResult);
    }

    private List<Stock> findStockEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Stock.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Stock findStock(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Stock.class, id);
        } finally {
            em.close();
        }
    }

    public int getStockCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Stock> rt = cq.from(Stock.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
